package com.pg.agent.engine.service.utils;

import com.alibaba.fastjson.JSONObject;
import com.pg.agent.engine.client.bo.InterfaceBO;
import com.pg.agent.engine.client.vo.HttpParam;
import com.pg.base.util.PgHttpUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * HttpClient工具类
 *
 * @author wangmx
 */
@Slf4j
public class HttpClientUtils {


    public static void sendSseEventStream(String eventData, HttpServletResponse response) throws IOException {
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("data: " + eventData + "\n\n");
        writer.flush();
    }

    public static String exeHttpCall(InterfaceBO interfaceBO, HttpParam httpParam) {
        String resultMessage = null;

        // get请求返回结果
        if (PgHttpUtil.GET.equals(interfaceBO.getRequestMethod())) {
            resultMessage = PgHttpUtil.get(interfaceBO.getUrl(), httpParam.getHeaders(), httpParam.getQuery());
        } else {
            //"http://server-decision-business-module.decision-itest.coding.clife.net:30000/education/multi-turn-similar"
            //"http://clife-ai-ml-edu-data-query.coding.clife.net:30000/education/child-info-extraction"
            if (interfaceBO.getBodyType() != null && interfaceBO.getBodyType() == 2){
                String url = interfaceBO.getUrl();
                if (httpParam.getQuery() != null){
                    url = PgHttpUtil.getUrlByParam(httpParam.getQuery(),url);
                }
                PgHttpUtil.postBody(interfaceBO.getUrl(), httpParam.getHeaders(), httpParam.getQuery(), httpParam.getPath(),JSONObject.toJSONString(httpParam.getBody()),1000*60);
            }else {
                resultMessage = PgHttpUtil.postBody(interfaceBO.getUrl(), httpParam.getHeaders(), httpParam.getQuery(), httpParam.getPath(),JSONObject.toJSONString(httpParam.getBody()),1000*60);
            }

        }

        return resultMessage;
    }

}